<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 商品评价系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .profile-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
        }
        .profile-avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            border: 4px solid white;
            object-fit: cover;
        }
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }
        .stats-card:hover {
            transform: translateY(-5px);
        }
        .stats-number {
            font-size: 2rem;
            font-weight: bold;
            color: #667eea;
        }
        .nav-pills .nav-link {
            border-radius: 25px;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        .nav-pills .nav-link.active {
            background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
        }
        .review-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border-radius: 10px;
        }
        .rating {
            color: #ffc107;
        }
        .btn-edit {
            background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
            border-radius: 25px;
        }
        .btn-edit:hover {
            background: linear-gradient(45deg, #5a6fd8 0%, #6a4190 100%);
            color: white;
        }
        .form-floating {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/product-review/page/index">
                <i class="fas fa-shopping-cart me-2"></i>商品评价系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/product-review/page/index">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/product-review/page/products">商品列表</a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i><span id="navUsername"></span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/product-review/page/user-center">个人中心</a></li>
                            <li><a class="dropdown-item" href="#" onclick="logout()">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container my-4">
        <!-- 个人信息头部 -->
        <div class="profile-header">
            <div class="row align-items-center">
                <div class="col-md-3 text-center">
                    <img src="/product-review/static/img/default-avatar.jpg" class="profile-avatar" id="userAvatar" alt="头像">
                </div>
                <div class="col-md-6">
                    <h2 id="userRealName">用户姓名</h2>
                    <p class="mb-1"><i class="fas fa-user me-2"></i>用户名：<span id="userUsername"></span></p>
                    <p class="mb-1"><i class="fas fa-envelope me-2"></i>邮箱：<span id="userEmail"></span></p>
                    <p class="mb-0"><i class="fas fa-phone me-2"></i>手机：<span id="userPhone"></span></p>
                </div>
                <div class="col-md-3 text-center">
                    <button class="btn btn-light btn-lg" onclick="showEditModal()">
                        <i class="fas fa-edit me-2"></i>编辑资料
                    </button>
                </div>
            </div>
        </div>

        <!-- 统计信息 -->
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="stats-number" id="totalReviews">0</div>
                    <div class="text-muted">我的评价</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="stats-number" id="avgRating">0.0</div>
                    <div class="text-muted">平均评分</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="stats-number" id="joinDays">0</div>
                    <div class="text-muted">加入天数</div>
                </div>
            </div>
        </div>

        <!-- 功能导航 -->
        <div class="row">
            <div class="col-md-3">
                <div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist">
                    <button class="nav-link active" id="v-pills-reviews-tab" data-bs-toggle="pill" 
                            data-bs-target="#v-pills-reviews" type="button" role="tab">
                        <i class="fas fa-comments me-2"></i>我的评价
                    </button>
                    <button class="nav-link" id="v-pills-favorites-tab" data-bs-toggle="pill" 
                            data-bs-target="#v-pills-favorites" type="button" role="tab">
                        <i class="fas fa-heart me-2"></i>我的收藏
                    </button>
                    <button class="nav-link" id="v-pills-orders-tab" data-bs-toggle="pill" 
                            data-bs-target="#v-pills-orders" type="button" role="tab">
                        <i class="fas fa-shopping-bag me-2"></i>我的订单
                    </button>
                    <button class="nav-link" id="v-pills-settings-tab" data-bs-toggle="pill" 
                            data-bs-target="#v-pills-settings" type="button" role="tab">
                        <i class="fas fa-cog me-2"></i>账户设置
                    </button>
                </div>
            </div>
            <div class="col-md-9">
                <div class="tab-content" id="v-pills-tabContent">
                    <!-- 我的评价 -->
                    <div class="tab-pane fade show active" id="v-pills-reviews" role="tabpanel">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h4>我的评价</h4>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-outline-primary active" onclick="filterMyReviews('all')">全部</button>
                                <button type="button" class="btn btn-outline-primary" onclick="filterMyReviews(5)">5星</button>
                                <button type="button" class="btn btn-outline-primary" onclick="filterMyReviews(4)">4星</button>
                                <button type="button" class="btn btn-outline-primary" onclick="filterMyReviews(3)">3星</button>
                                <button type="button" class="btn btn-outline-primary" onclick="filterMyReviews(2)">2星</button>
                                <button type="button" class="btn btn-outline-primary" onclick="filterMyReviews(1)">1星</button>
                            </div>
                        </div>
                        <div id="myReviewsList">
                            <!-- 评价列表将通过JavaScript动态加载 -->
                        </div>
                        <div class="text-center mt-4">
                            <button class="btn btn-outline-primary" id="loadMoreReviewsBtn" onclick="loadMoreMyReviews()" style="display: none;">
                                加载更多
                            </button>
                        </div>
                    </div>

                    <!-- 我的收藏 -->
                    <div class="tab-pane fade" id="v-pills-favorites" role="tabpanel">
                        <h4 class="mb-4">我的收藏</h4>
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-heart fa-3x mb-3"></i>
                            <p>收藏功能待完善</p>
                        </div>
                    </div>

                    <!-- 我的订单 -->
                    <div class="tab-pane fade" id="v-pills-orders" role="tabpanel">
                        <h4 class="mb-4">我的订单</h4>
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-shopping-bag fa-3x mb-3"></i>
                            <p>订单功能待完善</p>
                        </div>
                    </div>

                    <!-- 账户设置 -->
                    <div class="tab-pane fade" id="v-pills-settings" role="tabpanel">
                        <h4 class="mb-4">账户设置</h4>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="mb-0">修改密码</h5>
                                    </div>
                                    <div class="card-body">
                                        <form id="passwordForm">
                                            <div class="form-floating mb-3">
                                                <input type="password" class="form-control" id="oldPassword" placeholder="当前密码" required>
                                                <label for="oldPassword">当前密码</label>
                                            </div>
                                            <div class="form-floating mb-3">
                                                <input type="password" class="form-control" id="newPassword" placeholder="新密码" required>
                                                <label for="newPassword">新密码</label>
                                            </div>
                                            <div class="form-floating mb-3">
                                                <input type="password" class="form-control" id="confirmPassword" placeholder="确认新密码" required>
                                                <label for="confirmPassword">确认新密码</label>
                                            </div>
                                            <button type="button" class="btn btn-edit" onclick="changePassword()">修改密码</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="mb-0">账户信息</h5>
                                    </div>
                                    <div class="card-body">
                                        <p><strong>注册时间：</strong><span id="registerTime"></span></p>
                                        <p><strong>最后登录：</strong><span id="lastLoginTime"></span></p>
                                        <p><strong>账户状态：</strong><span id="accountStatus" class="badge bg-success">正常</span></p>
                                        <hr>
                                        <button class="btn btn-outline-danger" onclick="confirmDeleteAccount()">
                                            <i class="fas fa-trash me-2"></i>删除账户
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑资料模态框 -->
    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑个人资料</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editForm">
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" id="editRealName" placeholder="真实姓名" required>
                            <label for="editRealName">真实姓名</label>
                        </div>
                        <div class="form-floating mb-3">
                            <input type="email" class="form-control" id="editEmail" placeholder="邮箱" required>
                            <label for="editEmail">邮箱</label>
                        </div>
                        <div class="form-floating mb-3">
                            <input type="tel" class="form-control" id="editPhone" placeholder="手机号码">
                            <label for="editPhone">手机号码</label>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-edit" onclick="updateProfile()">保存修改</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-dark text-light py-4 mt-5">
        <div class="container">
            <div class="text-center">
                <p>&copy; 2024 商品评价系统. All rights reserved.</p>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // 全局变量
        let currentUser = null;
        let editModal = null;
        let reviewPage = 1;
        let reviewFilter = 'all';
        
        $(document).ready(function() {
            // 初始化模态框
            editModal = new bootstrap.Modal(document.getElementById('editModal'));
            
            // 检查登录状态
            checkLoginStatus();
        });
        
        // 检查登录状态
        function checkLoginStatus() {
            $.ajax({
                url: '/product-review/user/current',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        currentUser = result.data;
                        $('#navUsername').text(result.data.username);
                        
                        // 在获取到用户信息后再加载其他内容
                        loadUserInfo();
                        loadUserStats();
                        loadMyReviews();
                    } else {
                        alert('请先登录');
                        window.location.href = '/product-review/page/login';
                    }
                },
                error: function() {
                    alert('请先登录');
                    window.location.href = '/product-review/page/login';
                }
            });
        }
        
        // 加载用户信息
        function loadUserInfo() {
            console.log(currentUser);
            
            if (!currentUser) return;
            
            $('#userRealName').text(currentUser.realName || currentUser.username);
            $('#userUsername').text(currentUser.username);
            $('#userEmail').text(currentUser.email || '未设置');
            $('#userPhone').text(currentUser.phone || '未设置');
            
            // 设置编辑表单的默认值
            $('#editRealName').val(currentUser.realName || '');
            $('#editEmail').val(currentUser.email || '');
            $('#editPhone').val(currentUser.phone || '');
            
            // 设置账户信息
            if (currentUser.createTime) {
                $('#registerTime').text(new Date(currentUser.createTime).toLocaleDateString());
            }
            
            // 计算加入天数
            if (currentUser.createTime) {
                const joinDate = new Date(currentUser.createTime);
                const today = new Date();
                const diffTime = Math.abs(today - joinDate);
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                $('#joinDays').text(diffDays);
            }
            
            // 设置账户状态
            const statusMap = {
                'ACTIVE': { text: '正常', className: 'bg-success' },
                'INACTIVE': { text: '未激活', className: 'bg-warning' },
                'BANNED': { text: '已封禁', className: 'bg-danger' }
            };
            
            const status = statusMap[currentUser.status] || { text: '未知', className: 'bg-secondary' };
            $('#accountStatus').text(status.text).attr('class', `badge ${status.className}`);
        }
        
        // 加载用户统计信息
        function loadUserStats() {
            if (!currentUser) return;
            
            $.ajax({
                url: `/product-review/review/user/\${currentUser.id}`,
                type: 'GET',
                data: { page: 1, size: 1000 }, // 获取所有评价用于统计
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        const reviews = result.data.list || [];
                        const total = result.data.total || 0;
                        $('#totalReviews').text(total);
                        
                        // 计算平均评分
                        if (reviews.length > 0) {
                            const totalRating = reviews.reduce((sum, review) => sum + review.rating, 0);
                            const avgRating = (totalRating / reviews.length).toFixed(1);
                            $('#avgRating').text(avgRating);
                        } else {
                            $('#avgRating').text('0.0');
                        }
                    }
                }
            });
        }
        
        // 加载我的评价
        function loadMyReviews() {
            if (!currentUser) return;
            
            const params = {
                page: reviewPage,
                size: 10
            };
            
            if (reviewFilter !== 'all') {
                params.rating = reviewFilter;
            }
            
            $.ajax({
                url: `/product-review/review/user/\${currentUser.id}`,
                type: 'GET',
                data: params,
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        const reviews = result.data.list || [];
                        displayMyReviews(reviews, reviewPage === 1);
                        
                        // 检查是否还有更多评价
                        if (reviews.length === result.data.size && result.data.page < result.data.pages) {
                            $('#loadMoreReviewsBtn').show();
                        } else {
                            $('#loadMoreReviewsBtn').hide();
                        }
                    }
                }
            });
        }
        
        // 显示我的评价
        function displayMyReviews(reviews, replace = false) {
            if (reviews.length === 0 && replace) {
                $('#myReviewsList').html('<div class="text-center text-muted py-5"><i class="fas fa-comments fa-3x mb-3"></i><p>暂无评价</p></div>');
                return;
            }
            
            let html = '';
            reviews.forEach(function(review) {
                html += createMyReviewCard(review);
            });
            
            if (replace) {
                $('#myReviewsList').html(html);
            } else {
                $('#myReviewsList').append(html);
            }
        }
        
        // 创建我的评价卡片
        function createMyReviewCard(review) {
            const stars = generateStars(review.rating);
            const createTime = new Date(review.createTime).toLocaleDateString();
            const productName = review.productName || '商品名称';
            const content = review.content || '用户没有留下评价内容';
            const statusText = review.status === 1 ? '已审核' : '待审核';
            
            return `
                <div class="review-card card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <div>
                                <h6 class="mb-1">\${productName}</h6>
                                <div class="rating mb-2">\${stars}</div>
                            </div>
                            <div class="text-end">
                                <small class="text-muted">\${createTime}</small>
                                <div class="mt-1">
                                    <button class="btn btn-sm btn-outline-primary me-1" onclick="editReview(\${review.id})">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteReview(\${review.id})">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="review-content">
                            \${content}
                        </div>
                        <div class="mt-2">
                            <span class="badge bg-secondary">\${statusText}</span>
                        </div>
                    </div>
                </div>
            `;
        }
        
        // 生成星级显示
        function generateStars(rating) {
            let html = '';
            for (let i = 1; i <= 5; i++) {
                if (i <= rating) {
                    html += '<i class="fas fa-star"></i>';
                } else {
                    html += '<i class="far fa-star"></i>';
                }
            }
            return html;
        }
        
        // 筛选我的评价
        function filterMyReviews(rating) {
            reviewFilter = rating;
            reviewPage = 1;
            
            // 更新按钮状态
            $('#v-pills-reviews .btn-group button').removeClass('active');
            event.target.classList.add('active');
            
            loadMyReviews();
        }
        
        // 加载更多我的评价
        function loadMoreMyReviews() {
            reviewPage++;
            loadMyReviews();
        }
        
        // 显示编辑资料模态框
        function showEditModal() {
            editModal.show();
        }
        
        // 更新个人资料
        function updateProfile() {
            const realName = $('#editRealName').val().trim();
            const email = $('#editEmail').val().trim();
            const phone = $('#editPhone').val().trim();
            
            if (!realName) {
                alert('请输入真实姓名');
                return;
            }
            
            if (!email) {
                alert('请输入邮箱');
                return;
            }
            
            const userData = {
                realName: realName,
                email: email,
                phone: phone
            };
            
            $.ajax({
                url: `/product-review/user/update/${currentUser.id}`,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(userData),
                success: function(result) {
                    if (result.code === 200) {
                        alert('个人资料更新成功');
                        editModal.hide();
                        
                        // 更新当前用户信息
                        currentUser.realName = realName;
                        currentUser.email = email;
                        currentUser.phone = phone;
                        
                        // 重新加载用户信息显示
                        loadUserInfo();
                    } else {
                        alert('更新失败：' + result.message);
                    }
                },
                error: function() {
                    alert('更新失败');
                }
            });
        }
        
        // 修改密码
        function changePassword() {
            const oldPassword = $('#oldPassword').val();
            const newPassword = $('#newPassword').val();
            const confirmPassword = $('#confirmPassword').val();
            
            if (!oldPassword || !newPassword || !confirmPassword) {
                alert('请填写所有密码字段');
                return;
            }
            
            if (newPassword !== confirmPassword) {
                alert('新密码和确认密码不一致');
                return;
            }
            
            if (newPassword.length < 6) {
                alert('新密码长度至少6位');
                return;
            }
            
            const passwordData = {
                oldPassword: oldPassword,
                newPassword: newPassword
            };
            
            $.ajax({
                url: '/product-review/user/change-password',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(passwordData),
                success: function(result) {
                    if (result.code === 200) {
                        alert('密码修改成功，请重新登录');
                        logout();
                    } else {
                        alert('密码修改失败：' + result.message);
                    }
                },
                error: function() {
                    alert('密码修改失败');
                }
            });
        }
        
        // 编辑评价
        function editReview(reviewId) {
            alert('编辑评价功能待完善');
        }
        
        // 删除评价
        function deleteReview(reviewId) {
            if (confirm('确定要删除这条评价吗？')) {
                $.ajax({
                    url: `/product-review/review/delete/\${reviewId}`,
                    type: 'DELETE',
                    success: function(result) {
                        if (result.code === 200) {
                            alert('评价删除成功');
                            reviewPage = 1;
                            loadMyReviews();
                            loadUserStats();
                        } else {
                            alert('删除失败：' + result.message);
                        }
                    },
                    error: function() {
                        alert('删除失败');
                    }
                });
            }
        }
        
        // 确认删除账户
        function confirmDeleteAccount() {
            if (confirm('确定要删除账户吗？此操作不可恢复！')) {
                if (confirm('再次确认：删除账户将清除所有数据，确定继续吗？')) {
                    deleteAccount();
                }
            }
        }
        
        // 删除账户
        function deleteAccount() {
            $.ajax({
                url: `/product-review/user/delete/${currentUser.id}`,
                type: 'DELETE',
                success: function(result) {
                    if (result.code === 200) {
                        alert('账户删除成功');
                        window.location.href = '/product-review/page/index';
                    } else {
                        alert('删除失败：' + result.message);
                    }
                },
                error: function() {
                    alert('删除失败');
                }
            });
        }
        
        // 退出登录
        function logout() {
            $.ajax({
                url: '/product-review/user/logout',
                type: 'POST',
                success: function(result) {
                    if (result.code === 200) {
                        window.location.href = '/product-review/page/index';
                    } else {
                        alert('退出登录失败：' + result.message);
                    }
                },
                error: function() {
                    alert('退出登录失败');
                }
            });
        }
    </script>
</body>
</html>